package com.ap.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import java.io.StringWriter;

/**
 * @author Siva.Pochana
 */
public class JaxbUtil {

    private static final Logger log = LoggerFactory.getLogger(JaxbUtil.class);

    public static JaxbUtil newInstance() {
        return new JaxbUtil();
    }


    /**
     * @param clazz
     * @param value
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void javaToXML(Class clazz, Object value) {
        try {
            if (value == null || clazz == null) {
                log.info("either clazz or value is emply");
            }

            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            StringWriter sw = new StringWriter();

            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(new JAXBElement<Object>(new QName("uri", "local"), clazz, value), sw);
            System.out.println(sw.toString());
            log.info("Marshalled Msg :\n " + sw.toString());

        } catch (JAXBException ex) {
            ex.printStackTrace();
            log.error("JAXBException occurred Message [" + ex.getMessage() + "] and Cause [" + ex.getCause() + "]");
        }
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    public StringWriter javaToXMLForDistributor(Class clazz, Object value) {
        StringWriter sw = new StringWriter();
        try {
            if (value == null || clazz == null) {
                log.info("either clazz or value is emply");
            }

            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(new JAXBElement<Object>(new QName("uri", "local"), clazz, value), sw);
            log.info("Marshalled Msg :\n " + sw.toString());
        } catch (JAXBException ex) {
            ex.printStackTrace();
            log.error("JAXBException occurred Message [" + ex.getMessage() + "] and Cause [" + ex.getCause() + "]");
        }
        return sw;
    }

}
